package com.xaioran.security.config;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

@Component
public class MyPasswordEncoder implements PasswordEncoder {
    @Override
    //加密
    public String encode(CharSequence rawPassword) {
        return privteEncode(rawPassword);
    }

    @Override
    //核对密码
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        //对表单提交过来的密码进行加密
        String formPassword=privteEncode(rawPassword);
        //和数据库密码比较
        String DataBasePassword=encodedPassword;
        return Objects.equals(formPassword,DataBasePassword);
    }


    public   String privteEncode(CharSequence rawPassword){
        try {
            String algorithm="MD5";
            MessageDigest messageDigest=MessageDigest.getInstance(algorithm);
            //获取rawPassword的字节数组
            byte[] input=((String) rawPassword).getBytes();
            //加密之后的结果
            byte[] output=messageDigest.digest(input);
            //获取加密的结果转换位16进制
            String encode=new BigInteger(1,output).toString(16).toUpperCase()/*转大写*/;
            return encode;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

}


